package com.wika.basics.widget

import android.animation.ObjectAnimator
import android.animation.ValueAnimator
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.Matrix
import android.graphics.Paint
import android.graphics.Path
import android.graphics.PathMeasure
import android.graphics.RectF
import android.graphics.SweepGradient
import android.util.AttributeSet
import android.util.Log
import android.view.View
import android.view.animation.LinearInterpolator
import com.wika.basics.R
import com.wika.basics.utils.ViewUtils.dp2px

/**
 *@Description: 自定义圆形进度
 *@Date: 2024/7/24 17:27
 *@Author: WangWeiShuo
 */
class CircleProgressView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {

    private val ringPaint: Paint
    private val progressPaint: Paint
    private val bitmapPaint: Paint
    private val ringRectF: RectF = RectF()
    private var ringWidth = 4f
    private val bitmap: Bitmap
    private var path: Path
    private var pathMeasure: PathMeasure
    private var mMatrix = Matrix()
    private val defaultStartAngle = 0f
    private var currentStartAngle = defaultStartAngle
    private var progressSweepAngle = 0f
    private var currentRatio = 0f
    private var isGradual: Boolean = true
    private val degreeOfOnTurn = 360f
    private var animator: ValueAnimator? = null

    private var ringColor: Int
    private var progressColor: Int
    private var gradualStartColor: Int
    private var gradualEndColor: Int

    init {

        context.obtainStyledAttributes(attrs, R.styleable.CircleProgressBar).run {
            ringWidth =
                getDimensionPixelSize(
                    R.styleable.CircleProgressBar_circle_width,
                    dp2px(context,4f)
                ).toFloat()
            isGradual = getBoolean(R.styleable.CircleProgressBar_isGradual, false)
            ringColor = getColor(
                R.styleable.CircleProgressBar_circle_color,
                context.getColor(R.color.yellow_F2AF00)
            )
            progressColor =
                getColor(
                    R.styleable.CircleProgressBar_circle_progress_color,
                    context.getColor(R.color.colorAccent)
                )
            gradualStartColor =
                getColor(
                    R.styleable.CircleProgressBar_gradual_start_color,
                    context.getColor(R.color.colorAccent)
                )
            gradualEndColor =
                getColor(
                    R.styleable.CircleProgressBar_gradual_end_color,
                    context.getColor(R.color.colorPrimaryDark)
                )

            bitmap = BitmapFactory.decodeResource(
                resources,
                getResourceId(
                    R.styleable.CircleProgressBar_progress_thumb,R.drawable.icon_point_thump
                )
            )
            recycle()
        }

        ringPaint = Paint().apply {
            isAntiAlias = true
            style = Paint.Style.STROKE
            color = ringColor
            strokeWidth = ringWidth
            strokeCap = Paint.Cap.ROUND
        }
        progressPaint = Paint().apply {
            isAntiAlias = true
            style = Paint.Style.STROKE
            color = progressColor
            strokeWidth = ringWidth
            strokeCap = Paint.Cap.ROUND
        }
        bitmapPaint = Paint().apply {
            isAntiAlias = true
        }

        path = Path()
        pathMeasure = PathMeasure()
    }

    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)

        canvas?.save()

        // 移动、旋转
        canvas?.translate((width / 2).toFloat(), (height / 2).toFloat())
        canvas?.rotate(90f)

        // 绘制圆环
        canvas?.drawArc(ringRectF, 0f, degreeOfOnTurn, false, ringPaint)
        canvas?.drawArc(ringRectF, currentStartAngle, progressSweepAngle, false, progressPaint)

        // 球型图片
        pathMeasure.also {
            it.getMatrix(
                (it.length * (currentRatio / 100)) % it.length, mMatrix,
                PathMeasure.TANGENT_MATRIX_FLAG or PathMeasure.POSITION_MATRIX_FLAG
            )

            mMatrix.preTranslate((-bitmap.width / 2).toFloat(), (-bitmap.height / 2).toFloat())
            canvas?.drawBitmap(bitmap, mMatrix, bitmapPaint)
        }

        canvas?.restore()

    }

    /**
     * 暂停动画
     */
    fun pauseAnimator() {
        if (animator?.isPaused == true) return
        animator?.pause()
    }

    /**
     * 继续执行
     */
    fun resumeAnimator() {
        if (animator?.isPaused != true) return
        animator?.resume()
    }

    fun cancelAnimator() {
        if (animator?.isStarted != true) return
        animator?.cancel()
    }

    /**
     * 开始动画
     */
    private var currentValue = 0f
    fun startAnimator(animatorDuration: Long = 5) {
        animator = ObjectAnimator.ofFloat(currentValue, currentRatio * 360 / 100).apply {
            duration = 500
            interpolator = LinearInterpolator()
//            if (isGradual) {
//                repeatCount = Animation.INFINITE
//                repeatMode = ValueAnimator.RESTART
//            }
        }

        animator?.addUpdateListener {
            val value = it.animatedValue as Float
            Log.e("wws", "startAnimator: value = $value", )
            currentValue = value
            if (isGradual) { // 有渐变
                progressSweepAngle = progressSweepAngle.coerceAtLeast(value.coerceAtMost(90f))
                currentRatio = (value % degreeOfOnTurn) / degreeOfOnTurn * 100// 当前角度/360的比值
//                currentStartAngle = if (progressSweepAngle < 90) { // 起始角度
//                    defaultStartAngle
//                } else {
//                    (degreeOfOnTurn + value - 90f) % degreeOfOnTurn
//                }

                // 渐变处理
                val sweepGradient = SweepGradient(
                    ringRectF.centerX(),
                    ringRectF.centerY(),
                    intArrayOf(
                        gradualStartColor,
                        gradualEndColor
                    ),
                    floatArrayOf(0.75f, 1.0f) // 设置 0f，0.25f，起始点看起来被截断一样，所以用0.75f,1.0f，并再下方使用旋转处理
                )

                // 旋转
//                sweepGradient.setLocalMatrix(Matrix().apply {
//                    setRotate(
//                        if (value > 90f || progressSweepAngle >= 90) {
//                            value
//                        } else {
//                            90f
//                        },
//                        ringRectF.centerX(),
//                        ringRectF.centerY()
//                    )
//                })

                progressPaint.shader = sweepGradient

            } else {
                progressSweepAngle = it.animatedValue as Float
                currentRatio = value / degreeOfOnTurn * 100
                Log.e("wws", "startAnimator: progressSweepAngle = $progressSweepAngle,,,,currentRatio = $currentRatio", )
            }

            invalidate()
        }

        animator?.start()
    }

    fun setIsGradual(isGradual: Boolean) {
        this.isGradual = isGradual
    }

    fun setProgress(progress: Int){
        currentRatio = progress.toFloat()
        startAnimator()
    }

    fun getCurrentProgress(): Int{
        return currentRatio.toInt()
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        val width = MeasureSpec.getSize(widthMeasureSpec)
        val height = MeasureSpec.getSize(heightMeasureSpec)

        val result = width.coerceAtMost(height)
        setMeasuredDimension(result, result)

        val space = bitmap.width

        val radius = (result.toFloat() - space) / 2
        ringRectF.set(-radius, -radius, radius, radius)

        path.addCircle(0f, 0f, radius, Path.Direction.CW)

        pathMeasure.setPath(path, false)
    }
}